package com.example.lean;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private String cityCode;        //需要获取数据的城市代码
    private String resultJson = "";      //API返回的结果

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onGetClick(View view) {
        EditText editText = findViewById(R.id.edtxt_citycode);
        if (editText.getText().toString().length() > 0) {
            this.cityCode = editText.getText().toString();
            getWeatherInfo();
        } else {
            Toast.makeText(MainActivity.this, "清输入城市代码", Toast.LENGTH_SHORT).show();
        }
    }

    //调用互联网API获取天气信息，在Android 4.0以上，网络连接不能放在主线程上，不然就会报错android.os.NetworkOnMainThreadException
    //Android高版本联网失败报错:Cleartext HTTP traffic to xxx not permitted解决方法 参考：https://blog.csdn.net/gengkui9897/article/details/82863966
    public void getWeatherInfo() {
        Thread t = new Thread() {
            String path = "http://wthrcdn.etouch.cn/weather_mini?citykey=" + cityCode;

            @Override
            public void run() {
                //使用网址构造url
                URL url;
                try {
                    url = new URL(path);
                    //获取连接对象，做设置
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    //发送请求，获取响应码
                    if (conn.getResponseCode() == 200) {
                        //获取服务器返回的输入流
                        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        for (int c; (c = in.read()) >= 0; ) {
                            sb.append((char) c);
                        }
                        //发送消息至消息队列，主线程会执行handleMessage
                        Message msg = handler.obtainMessage();
                        msg.obj = sb.toString();
                        in.close();
                        resultJson = sb.toString();
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "获取城市代码:" + cityCode + "天气出错，出错信息:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            //handler消息队列中有数据会执行以下两行代码
            TextView txt = findViewById(R.id.txt);
            String[] weatherInfo = parseWeatherJosn(resultJson);
            if (weatherInfo != null) {
                txt.setText(convertArrayToString(weatherInfo, "\n") + "\n" + resultJson);
                Toast.makeText(MainActivity.this, "数据获取成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "数据获取失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //解析天气JSON格式数据
    public String[] parseWeatherJosn(String weatherJson) {
        JSONObject jsonObject;  //用于API的JSON数据操作的JSONObject成员变量
        JSONArray jsonArray;    //用于API的JSON数据操作的JSONArray成员变量
        String[] weatherInfo = null;   //用于保存各个界面的天气信息 weatherInfo[0]对应第一个界面weatherInfo[1]对应第二个界面
        //天气JSON数据解析并将不同的页面的天气信息保存到String weatherInfo[i]里
        //weatherInfo[i]=11日星期三,高温 23℃,<![CDATA[<3级]]>,低温 12℃,无持续风向,小雨,拉萨
        try {
            jsonObject = new JSONObject(weatherJson);
            jsonObject = jsonObject.getJSONObject("data");
            String cityName = jsonObject.getString("city");//获取城市
            jsonArray = jsonObject.getJSONArray("forecast");//获取最近5天天气数据
            weatherInfo = new String[5];
            for (int i = 0; i < 5; i++) {
                jsonObject = jsonArray.getJSONObject(i);
                weatherInfo[i] = "日期：" + jsonObject.getString("date") + ",";
                weatherInfo[i] += "最高温度：" + jsonObject.getString("high") + ",";
                weatherInfo[i] += "最低温度：" + jsonObject.getString("low") + ",";
                //weatherInfo[i] += "风力：" + jsonObject.getString("fengli") + ",";
                //风力数据为<![CDATA[<3级]]>，取出有用的部分<3级
                String[] fengliTemp = jsonObject.getString("fengli").split("]");
                String fengli = "";
                if (fengliTemp[0].length() > 9) {
                    fengli = fengliTemp[0].substring(9);
                    weatherInfo[i] += "风力：" + fengli;
                }
                weatherInfo[i] += "风向：" + jsonObject.getString("fengxiang") + ",";
                String type = jsonObject.getString("type");
                weatherInfo[i] += "天气：" + type + ",";
                weatherInfo[i] += "城市：" + cityName;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weatherInfo;
    }

    //字符串数组转换为字符串
    public String convertArrayToString(String[] strArr, String splitter) {
        if (strArr == null || strArr.length == 0) {
            return "";
        }
        String res = "";
        for (int i = 0, len = strArr.length; i < len; i++) {
            res += strArr[i];
            if (i < len - 1) {
                res += splitter;
            }
        }
        return res;
    }
}
